'use strict'
module.exports = function(grunt) {
  // pug和js文件变动自动重新编译和解析
  // 同时开启热加载
  grunt.initConfig({
    watch: {
      pug: {
        files: ['views/**'],
        options: {
          livereload: true
        }
      },
      js: {
        files: ['public/js/**', 'models/**/*.js', 'schemas/**/*.js'],
        tasks: ['jshint'],
        options: {
          livereload: true
        }
      }
    },
    jshint: {
      options: {
        jshintrc: './.jshintrc',
        ignores: ['public/libs/**/*.js', 'test/**/*.js']
      },
      all: ['public/js/*.js','app/**.*.js']
    },
    less: {
      development: {
        options: {
          compress: true,
          yuicompress: true,
          optimization: 2
        },
        files: {
          'public/build/index.css': 'public/less/index.less'
        }
      }
    },
    uglify: {
      development: {
        files: {
          'public/build/admin.min.js': 'public/js/admin.js',
          'public/build/categoryAdmin.min.js': 'public/js/categoryAdmin.js',
          'public/build/detail.min.js': [
            'public/js/detail.js'
          ]
        }
      }
    },
    // 在dev环境下实时监控 node app的执行情况
    // 发生异常 则重新在当前目录以3000端口下运行
    nodemon: {
      dev: {
        options: {
          file: 'app.js',
          args: [],
          ignoredFiles: ['README.md', 'node_modules/**', '.DS_Store'],
          watchedExtensions: ['js'],
          watchedFolders: ['./'],
          debug: true,
          delayTime: 1,
          env: {
            PORT: 3001
          },
          cwd: __dirname
        }
      }
    },

    // 将nodemon和watch并发执行
    concurrent: {
      target: {
        tasks: ['less','jshint','uglify','nodemon', 'watch'],
        options: {
          logConcurrentOutput: true
        }
      }
    },
    // 单元测试任务
    mochaTest: {
      options: {
        reporter:'spec'
      },
      src: ['test/**/*.js']
    }
  });

  // 监视到文件改动时触发其他任务
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-contrib-less');
  grunt.loadNpmTasks('grunt-contrib-uglify');
  // 监视node应用运行情况，发现停止自动重启
  grunt.loadNpmTasks('grunt-nodemon');
  // 优化慢任务，比如less、scss编译，nodemon和watch任务等并发运行，加快自动化任务的运行速度
  grunt.loadNpmTasks('grunt-concurrent');
  // mocha测试框架
  grunt.loadNpmTasks('grunt-mocha-test');

  // 使grunt不被警告和报错信息中断
  grunt.option('force', true);

  // 注册默认任务 'concurrent:target' 中间不能加空格
  // grunt 执行
  grunt.registerTask('default', ['concurrent:target']);

  // 注册单元测试任务 grunt test 执行
  grunt.registerTask('test', ['mochaTest']);
};
